package org.iabako.server.controller.timer.fixdata;

import org.apache.log4j.Logger;
import org.iabako.server.dao.business.SaleDAO;
import org.iabako.shared.entity.business.Sale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * Created by jose on 07/02/15.
 */

@Controller
public class InitializeInvoiceNumbersControllerTimer {

    static Logger log = Logger.getLogger(InitializeInvoiceNumbersControllerTimer.class.getName());

    @Autowired
    private SaleDAO saleDAO;

    @PersistenceContext(unitName = "MyPersistenceUnit")
    protected EntityManager entityManager;

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    //@Scheduled(initialDelay = 10000, fixedRate = 1000 * 60 * 60 * 24 * 10)
    public void action() throws Exception {
        log.info("Executing InitializeInvoiceNumbersControllerTimer...");
        try {
            String saleQuery = "SELECT sale FROM Sale sale WHERE sale.number IS NULL";
            List<Sale> saleList = entityManager.createQuery(saleQuery).getResultList();
            for (Sale sale : saleList) {
                if (sale.getNumber() == null) {
                    sale.setNumber(getNumber(sale.getId()));
                    saleDAO.persist(sale);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    }

    private String getNumber(Long count) {
        String number = count == null || count == 0 ? "1" : count + 1 + "";
        while (number.length() < 6) {
            number = "0" + number;
        }
        return number;
    }
}
